import plugin from '../../lib/plugins/plugin.js'
import { XiuXianData } from './xiuxian_data.js'
import { XiuXianUtils } from './xiuxian_utils.js'

export class XiuXianTasks extends plugin {
    constructor() {
        super({
            name: '修仙文游任务',
            dsc: '修仙游戏的任务相关功能',
            event: 'message',
            priority: 5000,
            rule: [
                { reg: '^查看任务$', fnc: 'showTasks' },
                { reg: '^完成任务(.*)$', fnc: 'completeTask' }
            ]
        })
        this.data = new XiuXianData()
        this.utils = new XiuXianUtils()
    }

    async showTasks(e) {
        const userId = e.user_id
        const player = this.data.gameState[userId]
        if (!player) return this.reply('请先输入"修仙"开始游戏')

        const taskList = this.data.tasks.map(task => {
            const progress = player.taskProgress?.[task.id] || 0
            return `${task.name}: ${task.description} (${progress}/${task.requirement})`
        }).join('\n')

        const taskText = `
当前任务:
${taskList}

使用"完成任务+任务名"来领取奖励
    `.trim()

        const forwardMsg = await this.utils.markdown(e, taskText, '修仙任务')
        return this.reply(forwardMsg)
    }

    async completeTask(e) {
        const userId = e.user_id
        const player = this.data.gameState[userId]
        if (!player) return this.reply('请先输入"修仙"开始游戏')

        const taskName = e.msg.replace(/^完成任务/, '').trim()
        const task = this.data.tasks.find(t => t.name === taskName)
        if (!task) return this.reply('任务不存在')

        if (!player.completedTasks) player.completedTasks = []
        if (player.completedTasks.includes(task.id)) return this.reply('该任务已完成')

        const progress = player.taskProgress?.[task.type] || 0
        if (progress < task.requirement) return this.reply(`任务未完成,当前进度:${progress}/${task.requirement}`)

        player.exp += task.reward.exp
        player.lingshi += task.reward.lingshi
        player.completedTasks.push(task.id)

        const newTask = this.utils.generateRandomTask()
        this.data.tasks.push(newTask)

        this.utils.saveJSON(this.data.paths.gameData, this.data.gameState)
        this.utils.saveJSON(this.data.paths.tasks, this.data.tasks)

        return this.reply(`恭喜完成任务"${taskName}"!获得${task.reward.exp}经验和${task.reward.lingshi}灵石。新任务"${newTask.name}"已添加。`)
    }
}
